package com.itheima1.controller;

import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import com.itheima1.Util.RandomUtil;
import com.itheima1.config.AliOssProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/validatecode")
public class SendSmsController {
    @Autowired
    private AliOssProperties smsUtil;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/send4Order")
    public String sendSms(@RequestParam("telephone") String phoneNumber) {
        try {
            Map<String, Integer> templateParam = new HashMap<>();
            int num =Integer.parseInt(RandomUtil.getSixBitRandom());
            templateParam.put("code",num);
            redisTemplate.opsForValue().set(phoneNumber, num + "");
            redisTemplate.expire(phoneNumber, 20, TimeUnit.MINUTES);



            String templateParamJson = new Gson().toJson(templateParam);

            SendSmsResponse sendSmsResponse = smsUtil.sendSms(phoneNumber, templateParamJson);
            String message = sendSmsResponse.getBody().getMessage();
            log.info("SMS sent successfully to phone number: {}, response message: {}", phoneNumber, message);
            return message;
        } catch (Exception e) {
            log.error("Failed to send SMS to phone number: {}", phoneNumber, e);
            return "Failed to send SMS: " + e.getMessage();
        }
    }
    @GetMapping("/send4Login")
    public String sendSms2(@RequestParam("telephone") String phoneNumber) {
        try {
            Map<String, Integer> templateParam = new HashMap<>();
            int num =Integer.parseInt(RandomUtil.getSixBitRandom());
            templateParam.put("code",num);
            redisTemplate.opsForValue().set(phoneNumber, num + "");
            redisTemplate.expire(phoneNumber, 20, TimeUnit.MINUTES);
            String templateParamJson = new Gson().toJson(templateParam);

            SendSmsResponse sendSmsResponse = smsUtil.sendSms(phoneNumber, templateParamJson);
            String message = sendSmsResponse.getBody().getMessage();
            log.info("SMS sent successfully to phone number: {}, response message: {}", phoneNumber, message);
            return message;
        } catch (Exception e) {
            log.error("Failed to send SMS to phone number: {}", phoneNumber, e);
            return "Failed to send SMS: " + e.getMessage();
        }
    }
}
